# ref: https://blog.csdn.net/tekin_cn/article/details/145965520
import multiprocessing as mp
import multiprocessing.shared_memory as shm
 
def read_mem(mem_name):
    print(' 读取测试 '.center(80, '*'))
    try:
        shared_mem = shm.SharedMemory(name=mem_name, create=False, size=102400)
        # 打印共享内存块的名称，以便在其他进程中访问
        read_data = bytes(shared_mem.buf[:])
        #shared_mem.close()
        print(f"共享内存名称: {shared_mem.name}") 
        #print(f"原始数据字节: {read_data}")
        print(f"原始字节长度: {len(read_data)} bytes")
        print(f"转字符串编码: {read_data.decode('utf-8')}")
    except:
        return

def write_mem(mem_name, content):
    print(' 写入测试 '.center(80, '*'))
    try:
        shared_mem = shm.SharedMemory(name=mem_name, create=False, size=102400)
        data = f'{content}\0'.encode("utf-8")
        shared_mem.buf[:len(data)] = data
        print(f"共享内存名称: {shared_mem.name}") 
        print(f"原始字节长度: {len(content)} bytes") 
        print(f"写入数据内容: {content}")
        #shared_mem.close() 
    except:
        return

read_mem('dongdongpet1')
write_mem('dongdongpet2', '{"name":"张三"}')

